﻿using System.Text;
using NH = NHibernate;
using NHibernate.Type;
using NHibernate.SqlTypes;
using System.Data;
using NHibernate.UserTypes;
using NHibernate;
using System;
using YasharEl.Infrastructure.Core.Personification;

namespace YasharEl.Infrastructure.Core.PersistenceModel.NHibernate.Personification.UserTypes
{
    public class IsraelIdentityNumberUserType : IUserType
    {
        public new bool Equals(object x, object y)
        {
            return x.Equals(y);
        }

        public int GetHashCode(object x)
        {
            return x.GetHashCode();
        }

        public object DeepCopy(object value)
        {
            return value;
        }

        public object Replace(object original, object target, object owner)
        {
            return original;
        }

        public object Assemble(object cached, object owner)
        {
            return cached;
        }

        public object Disassemble(object value)
        {
            return value;
        }

        public SqlType[] SqlTypes
        {
            get { return new[] { SqlTypeFactory.Int64 }; }
        }

        public Type ReturnedType
        {
            get { return typeof(IsraelIdentityNumber); }
        }

        public bool IsMutable
        {
            get { return false; }
        }

        public void NullSafeSet(IDbCommand cmd, object value, int index)
        {
            if (value == null)
            {
                NHibernateUtil.Int64.NullSafeSet(cmd, null, index);
            }
            else
            {
                NHibernateUtil.Int64.NullSafeSet(cmd, ((IsraelIdentityNumber)value).IdentityNumber, index);
            }
        }

        public object NullSafeGet(IDataReader rs, string[] names, object owner)
        {
            object identityNumberObject = NHibernateUtil.Int64.NullSafeGet(rs, names[0]);
            if (identityNumberObject == null)
                return null;

            string identityNumber = identityNumberObject.ToString();
            return IsraelIdentityNumber.Parse(identityNumber);
        }
    }
}
